﻿using System;
using System.Windows.Forms;
using UCore;

namespace Twin {
    public partial class frmWrArea : Form {

        public string GeneratedString { get; private set; }
        private string[] arg;
        
        private int INST_BITS = 0;
        private int INST_OP = 1;            //OP_WR_AREA, [cmfg], 1[area_name], [area_sn], k0=v0>k1=v1>kn=vn[kvs] 
        private int INST_CMFG = 2;
        private int INST_I_AREA = 3;
        private int INST_AREA_SN = 4;

        private int iChip;
        private XPort xport = new XPort();

        public frmWrArea(XPort xport, string content, int iChip){        
            InitializeComponent();

            this.iChip = iChip;
            this.xport = xport;

            GeneratedString = content;

            //dgvEdit
            dgvEdit.ColumnHeadersVisible = false;
            dgvEdit.AllowUserToAddRows = false;
            // 为DataGridView的MouseClick事件添加事件处理器
            dgvEdit.MouseClick += dgvEdit_MouseClick;

            arg = content.Split(',');

            arg[INST_I_AREA] = UI.init_cmbArea(cmbArea, arg[INST_I_AREA]);        
            arg[INST_CMFG] = UI.init_cmbCmfg(cmbCmfg, arg[INST_CMFG]);
            arg[INST_AREA_SN] = (Twin.TConsole.SnFile++).ToString("x");

            //UI.init_cmbCom(cmbCom, Ini.defaultPort);
            UI.init_listAbs(listAbs, cmbArea.SelectedIndex);
            UI.init_cmbSegSize(cmbSegSize, Ini.chip[iChip]);

            listAbs.MouseDoubleClick += ListAbs_MouseDoubleClick;
        }

        
        private void optWrArea_Load(object sender, EventArgs e) {
            //TopMost = true;
            FormBorderStyle = FormBorderStyle.FixedSingle; // 设置窗体边框样式为固定单线框
            MaximizeBox = false;   // 移除最大化按钮
            MinimizeBox = false;   // 禁止调整大小

            //显示芯片型号
            lblChip.Text += Ini.chip[iChip].name;

            TConsole.PositionFormAtTopRight(this);
        }


        private void dgvEdit_MouseClick(object sender, MouseEventArgs e) {
            // 检查是否是鼠标右键点击
            if (e.Button == MouseButtons.Right) {
                // 检查是否有当前行
                if (dgvEdit.CurrentRow != null) {
                    // 显示确认消息框
                    DialogResult result = MessageBox.Show("确定要删除当前行吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    // 如果用户点击了“是”，则删除当前行
                    if (result == DialogResult.Yes) {
                        dgvEdit.Rows.Remove(dgvEdit.CurrentRow);
                    }
                    // 删除当前行
                    //dgvEdit.Rows.Remove(dgvEdit.CurrentRow);
                }
            }
        }

        
        private void ListAbs_MouseDoubleClick(object sender, EventArgs e) {
            // 检查是否有选中的项
            if (listAbs.SelectedItem != null) {
                // 获取ListBox1中选中的项
                string selectedText = listAbs.SelectedItem.ToString();

                // 将选中的项添加到ListBox2的尾部
                //dgvEdit.Rows.Add(selectedText);

                // 将选中的项添加到DataGridView的尾部
                int newRow = dgvEdit.Rows.Add(selectedText);

                // 设置新行的第一列为选中状态
                dgvEdit.CurrentCell = dgvEdit.Rows[newRow].Cells[0];
            }
        }

        
        private void btnGenerate_Click(object sender, EventArgs e) {
            // 遍历DataGridView的所有行
            string s = "";
            foreach (DataGridViewRow row in dgvEdit.Rows) {
                // 检查行是否为新行（即用户可以添加但未提交的行）
                if (!row.IsNewRow) {
                    // 访问第一列的值
                    s += row.Cells[0].Value.ToString();
                    s += ">";
                    //Console.WriteLine(value); // 打印到控制台，或者可以进行其他操作
                }
            }
            if (!s.Equals("")) {
                //arg[INST_KVS] = s.Substring(0, s.Length - 1);
            }
            //GeneratedString = arg[INST_OP] + "," + arg[INST_CMFG] + "[cmfg]," + arg[INST_KVS] + "," + arg[INST_I_AREA] + "[i_area]," + arg[INST_AREA_SN] + "[area_sn]";
            this.Close();
        }


        private void cmbAreas_SelectedIndexChanged(object sender, EventArgs e) {
            string sIndex = cmbArea.SelectedIndex.ToString();
            int iFile = int.Parse(sIndex);
            if (iFile < Ini.size_of.area) {
                panel1.Visible = true;
                //
                UI.init_listAbs(listAbs, cmbArea.SelectedIndex);
            
            } else {
                switch (cmbArea.SelectedItem.ToString()) {
                    case "_MASS":
                    
                    case "_IAP":
                        panel1.Visible = false;
                        //
                        //UI.init_cmbFileSel(cmbBloc);
                        UI.init_cmbSegSize(cmbSegSize, Ini.chip[iChip]);
                        break;
                }
            }
            arg[INST_I_AREA] = sIndex;
        }


        private void cmbCmfg_SelectedIndexChanged(object sender, EventArgs e) {
            arg[INST_CMFG] = cmbCmfg.SelectedItem.ToString();
            if (arg[INST_CMFG].Equals("空")) {
                arg[INST_CMFG] = "";
            }
        }


        private string setKvs() {
            string s = "";

            for (int i = 0; i < dgvEdit.RowCount; i++) {
                DataGridViewRow row = dgvEdit.Rows[i];
                if (!row.IsNewRow) {
                    string value = row.Cells["abs"].Value.ToString();
                    s += value;
                    if (i < dgvEdit.RowCount - 1) {
                        s += ">";
                    }
                }
            }
            return s;
        }


        // AREA写(单帧)       =OP_WR_AREA, [cmfg], 1[i_area], [area_sn],   [k0:v0>k1:v1>kn:vn]			|0003	//
        // AREA写(多帧0)      =OP_WR_AREA, [cmfg], 1[i_area], [area_sn],   [seg][k0:v0>k1:v1>kn:vn]	|0003	//场景：全覆盖
        // AREA写(多帧)       =OP_WR_AREA, [cmfg], 1[i_area], [area_sn],   [seg][k0:v0>k1:v1>kn:vn]	|0003	//场景：全覆盖
        private void btnSend_Click(object sender, EventArgs e) {
            string wr_kvs = setKvs(); 

            //int iPort = int.Parse(cmbCom.Text.Replace("com", "")) - 1;
            CInfo cInfo = new CInfo();

            Msg.setInfo_bits(ref cInfo, arg[INST_BITS]);

            cInfo.sbCascade = chkWrAll.Checked ? "1" : "0";      //多帧(即使只有1帧，也按多帧编码)
            cInfo.sSegSize = cmbSegSize.SelectedItem.ToString();           //?是空值，实际是“128”，为什么？
            cInfo.sOpArgs = arg[INST_OP] + "," + arg[INST_CMFG] + "," + arg[INST_I_AREA] + "," + arg[INST_AREA_SN];    

            TConsole.sendAsProtocol(xport, ref cInfo, wr_kvs, "cobra");
        }






        //========================================================================================
        private void listAbs_SelectedIndexChanged(object sender, EventArgs e) {
        }

        private void label3_Click(object sender, EventArgs e) {
        }

        private void listAbs_SelectedIndexChanged_1(object sender, EventArgs e) {
        }

        private void btnGenerateTestFile_Click(object sender, EventArgs e) {
        }
    }
}
